<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      class="form-container"
      :disabled="isView"
    >
      <div class="createPost-main-container">
        <el-row gutter="80">
          <div class="postInfo-container">
            <el-col :span="12">
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="researchGroupName"
                  label-width="180px"
                  label="课题组名称："
                >
                  <el-input
                    v-model="postForm.researchGroupName"
                    :maxlength="100"
                    name="name"
                    required
                    placeholder="请输入课题组名称"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  label-width="180px"
                  label="课题组负责人："
                  prop="researchGroupOwnerId"
                >
                  <el-select
                    v-model="postForm.researchGroupOwnerId"
                    :remote-method="getUserList"
                    filterable
                    remote
                    placeholder="请选择负责人"
                    :loading="loading"
                    @change="changeUser"
                  >
                    <el-option
                      v-for="item in userListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="researchGroupOwnerPhone"
                  label-width="180px"
                  label="课题组负责人电话："
                >
                  <el-input
                    v-model="postForm.researchGroupOwnerPhone"
                    :maxlength="100"
                    name="name"
                    :disabled="true"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="researchGroupOwnerEmail"
                  label-width="180px"
                  label="课题组负责人邮箱："
                >
                  <el-input
                    v-model="postForm.researchGroupOwnerEmail"
                    :maxlength="100"
                    name="name"
                    :disabled="true"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row :span="12">
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="researchGroupCreatedDate"
                  label-width="180px"
                  label="成立日期："
                >
                  <el-date-picker
                    v-model="postForm.researchGroupCreatedDate"
                    type="date"
                    placeholder="请选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-row>
            </el-col>

            <el-col :span="12">
              <el-row>
                <el-form-item
                  label-width="180px"
                  label="课题组所在部门："
                  prop="researchGroupDepartment"
                >
                  <el-select
                    v-model="postForm.researchGroupDepartment"
                    :remote-method="getDepartmentList"
                    filterable
                    remote
                    placeholder="请选择部门"
                    :loading="loading"
                  >
                    <el-option
                      v-for="item in departmentListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="研究方向："
                >
                  <el-input
                    v-model="postForm.researchGroupDirection"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入研究方向"
                  />
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  label-width="180px"
                  prop="researchGroupSubject"
                  label="一级学科："
                >
                  <el-select
                    v-model="postForm.researchGroupSubject"
                    :remote-method="getSubjectList"
                    filterable
                    remote
                    placeholder="请选择一级学科"
                    :loading="loading"
                    required
                  >
                    <el-option
                      v-for="item in subjectListOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-row>
            </el-col>
          </div>
        </el-row>
        <el-row gutter="80">
          <el-form-item
              label-width="230px"
              label="课题组成员："
              class="postInfo-container-item"
              prop="researchGroupMembers"
            >
              <el-table
                class="members-table"
                :data="postForm.researchGroupMembers"
                border
              >
                <el-table-column label="队员身份" width="180px" align="center">
                  <template slot-scope="{ row }">
                    <el-select
                      v-model="row.userProjectRole"
                      filterable
                      remote
                      placeholder="请选择队员身份"
                      :loading="loading"
                      :remote-method="getMemberRoleList"
                      required
                    >
                      <el-option
                        v-for="item in memberRoleListOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="选择队员" width="100px" align="center">
                  <template slot-scope="scope">
                    <el-button round icon="el-icon-user-solid"
                      @click="selectUser(scope.$index)"
                    >
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="员工号" align="center" width="150px">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.employeeId"
                      :maxlength="100"
                      name="name"
                      :disabled="true"
                      required
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="姓名" align="center">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.userName"
                      :maxlength="100"
                      name="name"
                      :disabled="true"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="性别" align="center" width="100px">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.userGender"
                      :maxlength="100"
                      name="name"
                      :disabled="true"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="电话号码" align="center">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.userCellphone"
                      :maxlength="100"
                      name="name"
                      :disabled="true"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="身份证号码" align="center">
                  <template slot-scope="{ row }">
                    <el-input
                      v-model="row.userId"
                      :maxlength="100"
                      name="name"
                      :disabled="true"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column width="200px" align="center">
                  <template slot-scope="scope">
                    <div class="block float-right">
                      <el-button
                        v-loading="loading"
                        round
                        @click="removeItem(scope.row.id)"
                        icon="delete"
                      >
                        删除
                      </el-button>
                      <el-button
                        v-loading="loading"
                        round
                        v-if="
                          scope.$index + 1 ===
                          postForm.researchGroupMembers.length
                        "
                        @click="addItem(scope.$index)"
                      >
                        添加
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
        </el-row>
      </div>
      <el-dialog title="人员信息" class="user-dialog-container" :visible.sync="dialogTableVisible">
        <div class="filter-container">
          <el-input
            v-model="listQuery.searchKey1"
            placeholder="员工号"
            style="width: 200px"
            class="filter-item"
          />
          <el-input
            v-model="listQuery.searchKey2"
            placeholder="姓名"
            style="width: 200px"
            class="filter-item"
          />
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="searchAndSort"
          >
            检索
          </el-button>
        </div>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column label="" min-width="20px" align="center">
            <template slot-scope="{ row }">
              <el-radio :label="row.id" 
                v-model="radio"
                @change.native="singleSelection(row)">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column label="员工号" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.employeeId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="名字" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="性别" min-width="20px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userGender }}</span>
            </template>
          </el-table-column>
          <el-table-column label="电话号码" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userCellphone }}</span>
            </template>
          </el-table-column>
          <el-table-column label="身份证号码" min-width="50px" align="center">
            <template slot-scope="{ row }">
              <span class="link-type">{{ row.userId }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <el-button
        v-show="!isView"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
  </div>
</template>

<script>
import departmentList from "@/data/departments";
import subjectList from "@/data/subjects";
import memberRoles from "@/data/memberRoles";
import { fetchUserList } from "@/api/user";
import {
  fetchResearchGroupById,
  createResearchGroup,
  updateResearchGroup,
} from "@/api/research-group";
import { searchTwo } from "@/utils";

const defaultForm = {
  researchGroupName: "", // 课题组姓名
  researchGroupOwnerId: "", // 课题组负责人ID
  researchGroupOwnerName: "", // 课题组负责人名字
  researchGroupOwnerEmployeeId: "", // 课题组负责人员工编号
  researchGroupOwnerPhone: "", // 课题组负责人电话
  researchGroupOwnerEmail: "", // 课题组负责人邮箱
  researchGroupDepartment: "", // 课题组所属部门
  researchGroupDirection: "", // 课题组研究方向
  researchGroupCreatedDate: "", // 课题组成立时间
  researchGroupSubject: "", // 课题组一级学科
  researchGroupMembers: [], // 课题组成员
  id: undefined,
};

export default {
  name: "ResearchGroupDetail",
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (!value || value === "") {
        callback(new Error("此为必填项"));
      } else {
        callback();
      }
    };

    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      dialogTableVisible: false,
      userList: [],
      userListOptions: [],
      departmentListOptions: departmentList,
      subjectListOptions: subjectList,
      memberRoleListOptions: memberRoles,
      tableKey: 0,
      totalList: null,
      list: null,
      total: 0,
      currentMemberRowId: 0,
      listQuery: {
        pageIndex: 1,
        limit: 1000,
        searchField1: "employeeId",
        searchField2: "userName",
        searchKey1: "",
        searchKey2: "",
      },
      rules: {
        researchGroupName: [{ required: true, validator: validateRequire }],
        researchGroupOwnerPhone: [{ required: true, validator: validateRequire }],
        researchGroupDirection: [
          { required: true, validator: validateRequire },
        ],
        researchGroupOwnerId: [{ required: true, validator: validateRequire }],
        researchGroupCreatedDate: [
          { required: true, validator: validateRequire },
        ],
        researchGroupDepartment: [
          { required: true, validator: validateRequire },
        ],
        researchGroupMembers: [{ required: true, validator: validateRequire }],
        researchGroupSubject: [{ required: true, validator: validateRequire }],
      },
    };
  },
  created() {
    this.getUsers();
    this.postForm.researchGroupMembers.push({
        id: 0, // 用户id
        userProjectRole: null,
        employeeId: null, // 员工编号
        userName: null,
        userGender: null,
        userCellphone: null,
        userId: null, // 身份证
        researchGroupMemberId: null,
      });
    if (this.isEdit || this.isView) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }
  },
  methods: {
    getUsers() {
      this.listLoading = true;
      fetchUserList().then((res) => {
        this.totalList = res.data;
        this.userList = res.data.map((item) => {
          return {
            label: item.userName,
            value: item.id,
            phone: item.userCellphone,
            email: item.userEmail,
            employeeId: item.employeeId,
          };
        });
        this.userListOptions = this.userList;

        this.listLoading = false;
      });
    },
    getDepartmentList(query) {
      if (query !== "") {
        this.loading = true;
        this.departmentListOptions = departmentList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.departmentListOptions = departmentList;
      }
    },
    getSubjectList(query) {
      if (query !== "") {
        this.loading = true;
        this.subjectListOptions = subjectList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.subjectListOptions = subjectList;
      }
    },
    getUserList(query) {
      if (query !== "") {
        this.loading = true;
        this.userListOptions = userList.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.userListOptions = userList;
      }
    },
    getMemberRoleList(query) {
      if (query !== "") {
        this.loading = true;
        this.memberRoleListOptions = memberRoles.filter((item) => {
          return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
        });
        this.loading = false;
      } else {
        this.memberRoleListOptions = memberRoles;
      }
    },
    addItem(val) {
      let checkEmptyItems = this.postForm.researchGroupMembers.filter(
        (item) => item.employeeId === null || item.userProjectRole === null
      );
      if (
        checkEmptyItems.length >= 1 &&
        this.postForm.researchGroupMembers.length > 0
      ) {
        this.$message({
          message: "成员所有信息不能为空",
          type: "error",
        });
        return;
      }
      this.postForm.researchGroupMembers.push({
        id: val + 1,
        userProjectRole: null,
        employeeId: null,
        userName: null,
        userGender: null,
        userCellphone: null,
        userId: null,
        researchGroupMemberId: null
      });
    },
    removeItem(itemId) {
      if (this.postForm.researchGroupMembers.length > 1) {
        this.postForm.researchGroupMembers.splice(itemId, 1);
      } else {
        this.postForm.researchGroupMembers = [{
        id: null,
        userProjectRole: null,
        employeeId: null,
        userName: null,
        userGender: null,
        userCellphone: null,
        userId: null,
        researchGroupMemberId: null
       }];
      }
    },
    changeUser(val) {
      const selectedItem = this.userList.find((item) => {
        return item.value === val;
      });
      this.postForm.researchGroupOwnerName = selectedItem.label;
      this.postForm.researchGroupOwnerEmployeeId = selectedItem.employeeId;
      this.postForm.researchGroupOwnerPhone = selectedItem.phone;
      this.postForm.researchGroupOwnerEmail = selectedItem.email;
    },
    selectUser(val) {
      this.currentMemberRowId = val;
      this.dialogTableVisible = true;
      this.handleFilter();
    },
    handleFilter() {
      const result = searchTwo(this.totalList, this.listQuery);
      this.list = result.data;
      this.total = result.total;
    },
    searchAndSort() {
      this.listQuery.pageIndex = 1;
      this.handleFilter();
    },
    singleSelection(row) {
      this.postForm.researchGroupMembers.forEach((item) => {
        if (item.id === this.currentMemberRowId) {
          item.employeeId = row.employeeId;
          item.userName = row.userName;
          item.userGender = row.userGender;
          item.userCellphone = row.userCellphone;
          item.userId = row.userId;
          item.researchGroupMemberId = row.id;
        };
      });
      this.dialogTableVisible = false;
    },
    fetchData(id) {
      fetchResearchGroupById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.postForm.researchGroupMembers =
            this.postForm.researchGroupMembers?.length > 0
              ? JSON.parse(this.postForm.researchGroupMembers)
              : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      console.log(this.postForm);
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.postForm.researchGroupMembers =
            this.postForm.researchGroupMembers.filter((item) => {
              return item && item.employeeId && item.userProjectRole
            });
          if (this.$route.path.includes("create")) {
            createResearchGroup(this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/researchGroup/list");

                  this.$message({
                    title: "成功",
                    message: "课题组创建成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "课题组创建失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            updateResearchGroup(this.postForm.id, this.postForm)
              .then((res) => {
                if (res.data) {
                  this.$router.push("/researchGroup/list");
                  this.$message({
                    title: "成功",
                    message: "课题组信息更新成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "课题组信息更新失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          console.log("课题组信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}
</style>
